package com.cskaoyan.app.shiro;

import com.cskaoyan.app.service.AdminAuthService;
import com.cskaoyan.app.wxservice.WxAuthService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    AdminAuthService adminAuthService;

    @Autowired
    WxAuthService wxAuthService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomAuthToken token = (CustomAuthToken) authenticationToken;
        // 根据用户名查询库中（被加密以后的）密码
        String username = token.getUsername();
        String passwd = "";
        switch (token.getLoginType()) {
            case ADMIN_PASSWD:
                passwd = adminAuthService.getAdminPass(username);
                break;
            case WX_PASSWD:
                passwd = wxAuthService.getWxPass(username);
                break;
        }
        // 返回的认证信息包含了用户的用户名和密码
        return new SimpleAuthenticationInfo(username, passwd, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        // 读取用户的权限
        List<String> permissions = adminAuthService.getAdminPerm(primaryPrincipal);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }
}
